package com.lagou.edu.utils;

import com.lagou.edu.annotation.Service;

import java.sql.Connection;

/**
 * 饿汉式单例模式：构造函数私有化，被jvm加载的时候实例化
 */
@Service
public class ConnectionUtils {

/*    private ConnectionUtils() {
    }

    private static ConnectionUtils connectionUtils = new ConnectionUtils();

    public static ConnectionUtils getInstance(){
        return  connectionUtils;
    }*/

    //存储当前线程的连接
    private ThreadLocal<Connection> threadLocal = new ThreadLocal<>();



    /**
     * 从当前线程获取连接
     */
    public Connection getCurrentThreadConn() throws  Exception{
        //判断当前线程是否已经绑定连接，如果没有绑定，需要从连接池获取一个连接绑定到当前线程
        Connection connection = threadLocal.get();
        if(connection == null){
            //从连接池拿连接并绑定到线程
            connection = DruidUtils.getInstance().getConnection();
            //绑定到当前线程
            threadLocal.set(connection);
        }
        return  connection;
    }
}
